package com.kmia.bjs.flightserver.util;

import com.kmia.bjs.flightserver.config.BaseConfig;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.UUID;

/**
 * @param
 * @author 4K
 * @Description xml文档处理
 * @Version1.0
 * @date 2022/5/9 15:48
 * @return
 **/
@Slf4j
public class XMLUtil {

    public static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String formatXML(String unformattedXml) {
        try {
            final Document document = convertStringToDocument(unformattedXml);
            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            Writer out = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document);
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeXML(String content) {
        // 输出到文件
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString();
        if (content != null && !"".equals(content)) {
            try {
                File f = new File(BaseConfig.XMLPath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                f = new File(BaseConfig.XMLPath + "/" + fileName + ".xml");
                FileUtils.write(f, content, "utf8", false);
                log.info("创建xml文件：" + f.getAbsolutePath());
            } catch (IOException e) {
                log.error("创建xml文件出错：" + e);
            }
        }
    }

}
